package cn.bingoogolapple.bgabanner.demo;

import cn.bingoogolapple.bgabanner.demo.engine.Engine;
import ohos.aafwk.ability.AbilityPackage;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class App extends AbilityPackage {
    private static App sInstance;
    private Engine mEngine;
    private int connect = 10000;
    private int timeout = 10000;
    private PixelMap pixelMap = null;

    public static void setsInstance(App sInstance) {
        App.sInstance = sInstance;
    }

    @Override
    public void onInitialize() {
        super.onInitialize();
        setsInstance(this);
        mEngine = new Retrofit.Builder()
                .baseUrl("http://bgashare.bingoogolapple.cn/banner/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(Engine.class);
    }

    /**
     * get AbilityPackage Instance
     *
     * @return this
     */
    public static App getInstance() {
        return sInstance;
    }

    /**
     * getEngine
     *
     * @return Engine
     */
    public Engine getEngine() {
        return mEngine;
    }

    /**
     * get bitmap from url
     *
     * @param url
     * @return pixelmap
     */
    public PixelMap getBitmap(String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                pixelMap = getBitmapFromUrl(url);
            }
        }).start();
        return pixelMap;
    }

    /**
     * 根据Url获取网络图片资源
     *
     * @param url 图片url
     * @return PixelMap
     */
    public PixelMap getBitmapFromUrl(String url) {
        try {
            URLConnection conn = new URL(url).openConnection();
            conn.setConnectTimeout(connect);
            conn.setReadTimeout(timeout);
            InputStream is = conn.getInputStream();
            ImageSource source = ImageSource.create(is, new ImageSource.SourceOptions());
            ImageSource.DecodingOptions options = new ImageSource.DecodingOptions();
            PixelMap pixelMap = source.createPixelmap(options);
            is.close();
            return pixelMap;
        } catch (IOException e) {
            e.fillInStackTrace();
            return null;
        }
    }
}
